package com.jmu.bishe.service;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jmu.bishe.dao.SimpleHibernateDao;
import com.jmu.bishe.entity.Member;
import com.jmu.bishe.entity.News;
import com.jmu.bishe.utils.BeanUtils;
import com.jmu.bishe.utils.StringUtils;


@Service
@Transactional
public class UserService {
	
	private static Logger logger = Logger.getLogger(UserService.class);

	private SimpleHibernateDao<Member, String> userDao;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		//初始化DAO
		userDao = new SimpleHibernateDao<Member, String>(sessionFactory, Member.class);
	}

	

	
	private JdbcTemplate jdbcTemplate;
	
	@Resource(name = "jdbcTemplate")
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

    public Member getMember(String userName,String pwd){
//    	String sql = "select * from Member where USER_NAME=? and PASSWORD=?";
//    	List list = jdbcTemplate.queryForList(sql,new Object[]{userName,pwd});
//    	if(list.size()>0){
//    		Map map = (Map)list.get(0);
//    		Member member = new Member();
//    		member.setUserId((String)map.get("USER_ID"));
//    		member.setAddress(StringUtils.getObjectToString(map.get("ADDRESS")));
//    		//...
//    		return member;
//    	}else return null;
//    	Member m = userDao.get(userName);
//    	if(m!=null){
//	    	String p = m.getPassword();
//	    	if(p.equals(pwd)){
//	    		return m;
//	    	}
//    	}
    	
    	
    	List<Member> list = userDao.find("from Member where userId=? and password=?", userName,pwd);
    	if(list.size()>0){
    		return list.get(0);
    	}
    	
    	return null;
    }
    
    public Boolean saveOrUpdate(Member member){
    	try{
    		userDao.saveOrUpdate(member);
//    		userDao.get(id);
//   		    userDao.delete(entity);
//   		    userDao.find(hql, values)
//    		
//	    	String userId = member.getUserId();
//	    	Member m = userDao.get(userId);
//	    	if(m==null){
//	    		//增加
//	    		userDao.save(member);
//	    	}else{
//	    		//修改
//	    		BeanUtils.BeanToBean(member, m);
//	    	}
	    	return true;
    	}catch (Exception e) {
    		logger.info("保存用户异常",e);
			return false;
		}
    }

	public Member getMemberById(String userId) {
		List<Member> list = userDao.find("from Member where userId=?", userId);
    	if(list.size()>0){
    		return list.get(0);
    	}
    	
    	return null;
	}

}
